using System;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;

public class Bullet : MonoBehaviour
{
    public Player player;
    public float BulletBasicdamage; // 子弹基础伤害
    public float BulletBasicSpeed; // 子弹速度
    public GameObject explosionPrefab; // 爆炸特效

   
    public bool canSplit = true; // 是否可以分裂
    public float splitDamageMultiplier = 0.5f; // 分裂子弹的伤害倍率

    private Rigidbody2D rigidBody;

    private List<Collider2D> hitEnemies = new List<Collider2D>();
    
    void Awake()
    {
        player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>();
        rigidBody = GetComponent<Rigidbody2D>();
    }

    
    public void SetSpeed(Vector2 direction, float PlayerBulletSpeed, float tempBulletSpeed, float bulletSpeedModifier)
    {
        transform.right = direction; // 设置方向
        rigidBody.velocity = direction * (PlayerBulletSpeed + tempBulletSpeed) * BulletBasicSpeed * bulletSpeedModifier; // 设置速度
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Enemy")
        {
            if (hitEnemies.Contains(other))
            {
                // 如果已命中过，则跳过
                return;
            }

            Enemy enemy = other.GetComponent<Enemy>();
            if (enemy != null)
            {
                // 计算子弹造成的伤害
                float critResult = CalculateCritResult(player.stats.critRate, player.stats.critDamage);
                float bulletDamage = BulletBasicdamage * player.stats.PlayerAttackMultiplier * critResult / 100f;

                enemy.TakeDamage(bulletDamage); // 让敌人扣血

                // 将命中的敌人添加到列表
                hitEnemies.Add(other);
            }

            if (player.stats.splitCountForPlayer > 1 )
            {
                HandleSplit(other); // 传入命中的敌人作为参数
            }
            Destroy(gameObject);
        }
        else if (other.tag == "Boss")
        {
            // if (hitEnemies.Contains(other))
            // {
            //     // 如果已命中过，则跳过
            //     return;
            // }
            BossController boss = other.GetComponent<BossController>();
            if (boss != null)
            {
                // 计算子弹造成的伤害
                float critResult = CalculateCritResult(player.stats.critRate, player.stats.critDamage);
                float bulletDamage = BulletBasicdamage * player.stats.PlayerAttackMultiplier * critResult / 100f;

                boss.TakeDamage(bulletDamage); // 让敌人扣血

                // 将命中的敌人添加到列表
                hitEnemies.Add(other);
            }

            if (player.stats.splitCountForPlayer > 1 )
            {
                HandleSplit(other); // 传入命中的敌人作为参数
            }
            Destroy(gameObject);
        }
        else if (other.tag == "Walls")
        {
            // 命中墙直接销毁，不分裂
            Destroy(gameObject);
        }

        // 创建爆炸特效（可选）
        if (explosionPrefab != null)
        {
            Instantiate(explosionPrefab, transform.position, Quaternion.identity);
        }
    }

    //计算暴击伤害
    public float CalculateCritResult(float critRate, float critDamage)
    {
        float critResult;
        if (critRate < 100f)
        {
            critResult = Random.Range((150f + critDamage) * (critRate / 100f), 100f);
        }
        else if (critRate < 200f)
        {
            critResult = Random.Range((250f + critDamage) * ((critRate - 100f) / 100f), 150f + critDamage);
        }
        else if (critRate < 300f)
        {
            critResult = Random.Range((400f + critDamage) * ((critRate - 200f) / 100f), 250f + critDamage);
        }
        else
        {
            critResult = 400f * critDamage;
        }
        return critResult;
    }


    private void HandleSplit(Collider2D originalTarget)
    {
        if (!canSplit) return;

        canSplit = false; // 禁止分裂子弹再次分裂

        // 计算每个子弹的角度，原子弹不算在内
        float angleStep = 360f / player.stats.splitCountForPlayer; // 分裂子弹的角度间隔
        float startAngle = -angleStep * (player.stats.splitCountForPlayer / 2f); // 起始角度

        // 生成分裂的子弹
        for (int i = 0; i < player.stats.splitCountForPlayer; i++)
        {
            float angle = startAngle + i * angleStep;
            Vector2 direction = Quaternion.Euler(0, 0, angle) * transform.right; // 计算分裂后的方向

            GameObject splitBullet = Instantiate(gameObject, transform.position, Quaternion.identity); // 生成新的子弹
            Bullet splitBulletScript = splitBullet.GetComponent<Bullet>();

            // 设置分裂子弹的伤害和速度
            splitBulletScript.BulletBasicdamage = BulletBasicdamage * splitDamageMultiplier; // 分裂子弹伤害调整
            splitBulletScript.canSplit = false; // 禁止分裂子弹再次分裂
            splitBulletScript.hitEnemies.Add(originalTarget); // 添加原命中的敌人到新的子弹中
            splitBulletScript.SetSpeed(direction, player.stats.bulletSpeed, player.stats.tempBulletSpeed, player.stats.bulletSpeedModifier); // 设置分裂子弹的速度

            // 为每个新生成的分裂子弹添加命中敌人销毁逻辑
            Destroy(splitBullet, 2.0f); // 确保生成的分裂子弹在2秒后自动销毁以防止永远存在的子弹
        }

        Destroy(gameObject); // 销毁原子弹
    }
}
